<?php
require_once(CORE_DIR.'Common.php');
require_once(CORE_DIR.'mappers/TaskPointMapper.php');

class taskpointModel extends Model{
	
	function __construct(){
		$this->conn = $this->getConnection();
	}
	
	function addTaskPoint($pointTypeID, $taskID, $point){
		$query = "insert into taskpoint (pointTypeID, taskID, point) values ('%d', '%d', '%d')";
		$query = $this->format($query, array($pointTypeID, $taskID, $point));
		return $this->execute($query, new TaskPointMapper());	
	}	
	
	function updateTaskPoint($pointTypeID, $taskID, $point){
		//$query = "update taskpoint set point='%d', pointTypeID=%d where taskID=%d";
		$query = "replace into taskpoint (taskID, pointTypeID, point) values (%d, %d, %d)";
		$query = $this->format($query, array($taskID, $pointTypeID, $point));		
		return $this->execute($query, new TaskPointMapper());
	}

	function deleteTaskPoint($taskID, $pointTypeID = ""){
		$query = "delete from taskpoint where taskID=%d";
		$query = $this->format($query, array($taskID));

		if ( $pointTypeID != "" )
			$query .= " AND pointTypeID=".$pointTypeID;
		
		return $this->execute($query, new TaskPointMapper());
	}		
	
	function getTaskPointByTaskId($taskID){
		$query = "SELECT * FROM taskpoint WHERE taskID=%d ORDER BY point";	
		$query = $this->format($query, array($taskID));		
		return  $this->execute($query, new TaskPointMapper());
	}
	 
	function getTaskPointByTypeID($pointTypeID){
		$query = "SELECT * FROM taskpoint WHERE pointTypeID=%d ORDER BY point";	
		$query = $this->format($query, array($pointTypeID));	
		return $this->execute($query, new TaskPointMapper());
	}	
	
	function getTaskPointByTaskIdAndTypeID($pointTypeID, $taskID){
		$query = "SELECT * FROM taskpoint WHERE  pointTypeID=%d and taskID=%d ";	
		$query = $this->format($query, array($pointTypeID, $taskID));	
		return $this->execute($query, new TaskPointMapper());
	}
	
	function getUserPointsById($userID) {
		$query = "SELECT SUM(tp.point) AS point
			FROM taskuser tu 
			LEFT JOIN task t ON t.id = tu.taskId
			LEFT JOIN taskpoint tp ON t.id = tp.taskID
			WHERE tu.userId = %d AND t.status = 1 AND tp.point <> 'null'";
		
		$query = $this->format($query, array($userID));
		$list =  $this->execute($query, new TaskPointMapper());
		return  $list[0]->getPoint();
	}   
	
	function getUserPoints($userId) {
		$query = "
			SELECT sum(tp.point) as point, 
						tp.pointTypeID as pointTypeID,
						tp.taskID as taskID
			FROM taskpoint tp join task t on t.id=tp.taskID 
			join pointtype pt on tp.pointTypeID=pt.pintTypeID 
			join taskuser tu on t.id=tu.taskId 
			where (tu.userId=%d or tu.owner=%d) and t.status=1 group by tp.pointTypeID";	
		$query = $this->format($query, array($userId, $userId));	

		return $this->execute($query, new TaskPointMapper());
	}	
	
}
?>
